<template>
    <view class="pub_page pub_page_bg pub_chat_group_member pub_header_padding">
        <pub-head headerName="chat_group_member" :headerConfig="headerConfig" @headerBack="headerBack"></pub-head>
        <pub-dialog v-show="dialogShow" dialogName="chat_group_member" :dialogConfig="dialogConfig"
            @dialogBack="dialogBack"></pub-dialog>
        <div class="pub_page_scroll page_box">
            <scroll-view v-if="openType==1" scroll-y="true" class="lis_div">
                <div class="lis">
                    <div class="li" v-for="(cli, ckey) in friendList" :key="ckey" @click="liClick(cli,ckey)">
                        <div class="choose" :class="cli.noChoose ? 'choose_disabled' : ''">
                            <span class="icon-font-basic"
                                :class="cli.isChoose ? 'icon-b-select-6' : 'icon-b-select-4'"></span>
                        </div>
                        <pub-image class="img" :src="cli.userAvatar"></pub-image>
                        <div class="text">
                            <div class="name">{{ cli.userName }}</div>
                        </div>
                    </div>
                </div>
            </scroll-view>
            <scroll-view v-if="openType==2||openType==3" scroll-y="true" class="lis_div" @scrolltolower="scrollTolower">
                <!-- <div class="search_div" v-if="openType==2">
                    <div class="input_box">
                        <input v-model="keyword" class="input" type="text" placeholder="请输入昵称"
                            @confirm="headerClick('search')" @input="keywordChange">
                    </div>
                    <div class="btn" @click="headerClick('search')"></div>
                </div> -->
                <div class="lis">
                    <div class="li" :class="openType==3?'li-nochoose':''" v-for="(cli, ckey) in chatGroupMemberList"
                        :key="ckey" @click="liClick(cli,ckey)">
                        <div class="choose" v-if="openType==2">
                            <span class="icon-font-basic"
                                :class="cli.isChoose ? 'icon-b-select-6' : 'icon-b-select-4'"></span>
                        </div>
                        <pub-image class="img" :src="cli.userAvatar"></pub-image>
                        <div class="text">
                            <div class="name">{{ cli.userName }}</div>
                        </div>
                    </div>
                </div>
            </scroll-view>
        </div>
    </view>
</template>

<script>
export default {
    data() {
        return {
            pagescrollTop: 0,
            headerConfig: {
                title: '',//标题栏内容
                left_type: 3,
                right_type: 1,
                right_content: '',
                right_color: ''
            },
            dialogShow: false,
            dialogType: '',
            dialogConfig: {
                title: '提示',//标题栏内容
                content: ''
            },

            openType: 1,//1添加群成员  2删除群成员  3群成员列表
            openTypeName: ['', '选择联系人', '群成员列表', '群成员列表'],
            groupId: '',
            chatGroupMemberList: [],
            friendList: [],

            userIdList: [],//所选择的用户id、

            maxChoose: 0,//添加好友时最大可选择的数量

            isLoad: false,
        };
    },
    onLoad(options) {
        console.log("options", options);
        this.openType = options.openType || 1;
        this.headerConfig.title = this.openTypeName[this.openType];
        if (this.openType == 1 || this.openType == 2) {
            this.headerConfig.right_content = this.openType == 1 ? '确定' : '删除';
            this.headerConfig.right_color = this.openType == 1 ? '#4E89FE' : '#FF2933';
        }

        this.maxChoose = Number(options.maxChoose) || 0;

        this.groupId = options.groupId || '';
        if (this.groupId) {
            const that = this;
            if (this.openType == 1) {
                that.getFriendList();
            } else if (this.openType == 2 || this.openType == 3) {
                that.getGroupMemberList();
            }
        }
    },
    onPageScroll(res) {
        this.pagescrollTop = res.scrollTop;
    },
    methods: {
        scrollTolower(e) {
            console.log(e);
            if (this.isLoad) return;
            this.isLoad = true;
            this.getGroupMemberList();
        },
        getGroupMemberList() {
            const that = this;
            that.$txChat.getGroupMemberList({
                groupID: that.groupId,
                role: that.$TencentCloudChat.TYPES.GRP_MBR_ROLE_MEMBER,
                count: 100,
                offset: that.chatGroupMemberList.length,
            }).then(function (imResponse) {
                console.log("chat-getGroupMemberList", imResponse.data.memberList); // 群成员列表
                const memberList = imResponse.data.memberList;
                that.isLoad = false;
                const chatGroupMemberList = memberList.map(li => {
                    return {
                        userName: li.nick,
                        userAvatar: li.avatar,
                        userId: li.userID,
                        isChoose: false,
                    }
                });
                that.chatGroupMemberList = that.chatGroupMemberList.concat(chatGroupMemberList);
            }).catch(function (imError) {
                console.warn('getGroupMemberList error:', imError);
                that.isLoad = false;
            });
        },
        getFriendList() {
            const that = this;
            that.$txChat.getFriendList().then(function (imResponse) {
                const fList = imResponse.data; // 好友列表

                for (let i = 0; i < fList.length; i += 50) {
                    let userList = fList.slice(i, i + 50);
                    // console.log(1, userList);

                    that.$txChat.getGroupMemberProfile({
                        groupID: that.groupId,
                        userIDList: userList.map(li => {
                            return li.profile.userID
                        }),
                    }).then(function (imResponse) {
                        // console.log(imResponse.data.memberList); // 群成员列表
                        const groupMemberList = imResponse.data.memberList;

                        // 已经邀请进群的好友不显示
                        const friendList = userList.filter(li => {
                            let find = groupMemberList.find(mli => {
                                return mli.userID == li.profile.userID;
                            })
                            return find ? false : true
                        }).map(li => {
                            return {
                                userName: li.profile.nick,
                                userAvatar: li.profile.avatar,
                                userId: li.profile.userID,
                                isChoose: false,
                                noChoose: false
                            }
                        });
                        that.friendList = that.friendList.concat(friendList);

                        // 已经邀请进群的好友显示
                        // const friendList = userList.map(li => {
                        //     let find = groupMemberList.find(mli => {
                        //         return mli.userID == li.profile.userID;
                        //     })
                        //     return {
                        //         userName: li.profile.nick,
                        //         userAvatar: li.profile.avatar,
                        //         userId: li.profile.userID,
                        //         isChoose: find ? true : false,
                        //         noChoose: find ? true : false
                        //     }
                        // });

                        // that.friendList = that.friendList.concat(friendList);
                    }).catch(function (imError) {
                        console.warn('getGroupMemberProfile error:', imError);
                    });
                }
            }).catch(function (imError) {
                console.warn('getFriendList error:', imError); // 获取好友列表失败的相关信息
            });
        },
        liClick(info, key) {
            if (this.openType == 1) {
                if (info.noChoose) return;
                if (!info.isChoose) {
                    let arr = this.friendList.filter(li => {
                        return li.isChoose && !li.noChoose
                    })
                    if (arr.length == this.maxChoose) {
                        this.$comFun.toast(`最多可选择${this.maxChoose}个`);
                        return;
                    }
                }
                this.friendList[key].isChoose = !info.isChoose;
            } else if (this.openType == 2) {
                this.chatGroupMemberList[key].isChoose = !info.isChoose;
            } else if (this.openType == 3) {
                this.$comFun.openWin('/pages/mine/friend_center', { userId: info.userId })
            }
        },
        headerBack(data) {
            if (data.type == 'right') {
                let userIdList = [];
                if (this.openType == 1) {
                    userIdList = this.friendList.filter(li => {
                        return !li.noChoose && li.isChoose
                    }).map(li => {
                        return li.userId
                    })
                } else if (this.openType == 2) {
                    userIdList = this.chatGroupMemberList.filter(li => {
                        return li.isChoose
                    }).map(li => {
                        return li.userId
                    })
                }
                if (userIdList.length == 0) {
                    this.$comFun.toast('请选择');
                    return;
                }
                this.userIdList = userIdList;
                console.log(userIdList);
                if (this.openType == 1) {
                    this.chatDeal('to_add');
                } else if (this.openType == 2) {
                    this.chatDeal('to_delete');
                }
            }
        },
        dialogBack(data) {
            // console.log(data);
            this.dialogShow = false;
            if (data.name == 'chat_group_member' && data.key == 1) {
                this.chatDeal(this.dialogType)
            }
        },
        async chatDeal(type, data) {
            const that = this;
            switch (type) {
                case 'to_delete':
                    that.dialogShow = true;
                    that.dialogType = 'sure_delete',
                        that.dialogConfig = {
                            title: '提示',//标题栏内容
                            content: '是否确定删除所选得群成员？'
                        }
                    break;
                case 'sure_delete':
                    that.dialogShow = false;

                    that.$comFun.openLoading();
                    const res_1 = await that.$request.post('chat/deleteGroupUser', {
                        userIds: this.userIdList,
                        groupNumber: that.groupId
                    });
                    that.$comFun.closeLoading();
                    if (res_1.code == 200) {
                        that.$comFun.toast('删除成功');
                        uni.$emit('dealGroupMember', {
                            type: 'delete',
                            num: this.userIdList.length
                        });
                        setTimeout(() => {
                            that.$comFun.closeWin();
                        }, 1000);
                    } else {
                        that.$comFun.toast(res_1.message || "失败，请稍后再试");
                    }
                    break;
                case 'to_add':
                    that.dialogShow = true;
                    that.dialogType = 'sure_add',
                        that.dialogConfig = {
                            title: '提示',//标题栏内容
                            content: '是否确定添加所选的好友？'
                        }
                    break;
                case 'sure_add':
                    that.dialogShow = false;

                    that.$comFun.openLoading();
                    const res = await that.$request.post('chat/addGroupUser', {
                        userIds: this.userIdList,
                        groupNumber: that.groupId
                    });
                    that.$comFun.closeLoading();
                    if (res.code == 200) {
                        that.$comFun.toast('添加成功');
                        uni.$emit('dealGroupMember', {
                            type: 'add',
                            num: this.userIdList.length
                        });
                        setTimeout(() => {
                            that.$comFun.closeWin();
                        }, 1000);
                    } else {
                        that.$comFun.toast(res.message || "失败，请稍后再试");
                    }
                    break;
                default:
                    break;
            }
        }
    },
};
</script>

<style lang="scss" scoped>
@import "@/common/css/chat.scss";
</style>
